import requests
import pandas as pd
from datetime import datetime, timedelta
import time

API_KEY = '849aa9534ece4611af483035935a9a30'
LAT = 30.9336
LON = 113.922
START_DATE = '2024-01-01'
END_DATE = '2024-06-05'
BASE_URL = 'https://api.weatherbit.io/v2.0/history/hourly'

def fetch_weather_data(lat, lon, start_date, end_date, api_key, retries=3):
    params = {
        'lat': lat,
        'lon': lon,
        'start_date': start_date,
        'end_date': end_date,
        'key': api_key,
        'tz': 'local'
    }
    for _ in range(retries):
        try:
            response = requests.get(BASE_URL, params=params)
            response.raise_for_status()
            data = response.json()
            records = data['data']
            df = pd.DataFrame(records)
            df = df[['timestamp_local', 'temp']]
            df.rename(columns={'timestamp_local': 'date', 'temp': 'temperature'}, inplace=True)
            df['date'] = pd.to_datetime(df['date'])
            df.set_index('date', inplace=True)
            df.to_excel('temperature_data.xlsx')
            return df
        except requests.exceptions.RequestException as e:
            print(f"Error: {e}. Retrying...")
            time.sleep(5)
    raise ConnectionError("Failed to retrieve data after multiple attempts")

weather_df = fetch_weather_data(LAT, LON, START_DATE, END_DATE, API_KEY)
print(weather_df.head())
